﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Runtime.InteropServices;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace CoTuong
{
    public class SubMenu : Microsoft.Xna.Framework.DrawableGameComponent
    {
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern uint MessageBox(IntPtr hWnd, String text, String caption, uint type);

        VanCo vanco;

        #region Sprites, Position
        SpriteBatch spriteBatch;
        Texture2D SubMenuTexture;
        Texture2D btnThoat;
        Texture2D btnLuu;
        Texture2D btnBack;

        Vector2 SubMenu_Position;
        Vector2 btnThoat_Position;
        Vector2 btnluu_Position;
        Vector2 btnBack_Position;
        #endregion

        bool isThoatOnHover;
        bool isLuuOnHover;
        bool isBackOnHover;
        bool GameSaveRequested = false;
        bool ExitToMenuRequested = false;

        public static bool ReturnGame;

        public enum typeSaveGame {SaveData, HighScoreData};
        IAsyncResult asyncResult;
        PlayerIndex playerIndex = PlayerIndex.One;

        public SubMenu(Game game) : base(game)
        { 
        }
        public SubMenu(Game game, VanCo vanco)
            : base(game)
        {
            this.vanco = vanco;
        }

        public override void Initialize()
        {
            ReturnGame = false;
            base.Initialize();
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(Game.GraphicsDevice);
            SubMenuTexture = Game.Content.Load<Texture2D>(@"Images\Menu");
            btnThoat = Game.Content.Load<Texture2D>(@"Images\Button\ExitToMenuButton");
            btnLuu = Game.Content.Load<Texture2D>(@"Images\Button\SaveButton");
            btnBack = Game.Content.Load<Texture2D>(@"Images\Button\ResumeGameButton");

            SubMenu_Position.X = Game.Window.ClientBounds.Width / 2 - SubMenuTexture.Width / 2;
            SubMenu_Position.Y = Game.Window.ClientBounds.Height / 2 - SubMenuTexture.Height / 2;

            btnThoat_Position.X = SubMenu_Position.X + SubMenuTexture.Width / 2 - btnThoat.Width / 2;
            btnThoat_Position.Y = SubMenu_Position.Y + SubMenuTexture.Height - btnThoat.Height * 5;

            btnluu_Position.X = SubMenu_Position.X + SubMenuTexture.Width / 2 - btnLuu.Width / 2;
            btnluu_Position.Y = SubMenu_Position.Y + btnLuu.Height * 7;

            btnBack_Position.X = SubMenu_Position.X + SubMenuTexture.Width / 2 - btnBack.Width / 2;
            btnBack_Position.Y = SubMenu_Position.Y + SubMenuTexture.Height / 5;

            base.LoadContent();
        }

        public override void Update(GameTime gameTime)
        {
            try
            {
                #region Xử lý hơ chuột
                //Thoát On Hover
                if (Game1.mousePosition.X > btnThoat_Position.X && Game1.mousePosition.X < (btnThoat_Position.X + btnThoat.Width)
                    && Game1.mousePosition.Y > btnThoat_Position.Y && Game1.mousePosition.Y < (btnThoat_Position.Y + btnThoat.Height))
                    isThoatOnHover = true;
                else
                    isThoatOnHover = false;

                //Lưu On Hover
                if (Game1.mousePosition.X > btnluu_Position.X && Game1.mousePosition.X < (btnluu_Position.X + btnLuu.Width)
                    && Game1.mousePosition.Y > btnluu_Position.Y && Game1.mousePosition.Y < (btnluu_Position.Y + btnLuu.Height))
                    isLuuOnHover = true;
                else
                    isLuuOnHover = false;

                //Back On Hover
                if (Game1.mousePosition.X > btnBack_Position.X && Game1.mousePosition.X < (btnBack_Position.X + btnBack.Width)
                    && Game1.mousePosition.Y > btnBack_Position.Y && Game1.mousePosition.Y < (btnBack_Position.Y + btnBack.Height))
                    isBackOnHover = true;
                else
                    isBackOnHover = false;
                #endregion

                #region Xử lý nút thoát
                if (Game1.mouseClickedPosition.X > btnThoat_Position.X && Game1.mouseClickedPosition.X < (btnThoat_Position.X + btnThoat.Width)
                    && Game1.mouseClickedPosition.Y > btnThoat_Position.Y && Game1.mouseClickedPosition.Y < (btnThoat_Position.Y + btnThoat.Height))
                {
                    //Thoát và trở về Menu chính

                    if ((!Guide.IsVisible) && (ExitToMenuRequested == false))
                    {
                        ExitToMenuRequested = true;
                        asyncResult = Guide.BeginShowStorageDeviceSelector(playerIndex,
                            null, null);
                    }

                    if (ExitToMenuRequested && asyncResult.IsCompleted)
                    {
                        StorageDevice device = Guide.EndShowStorageDeviceSelector(asyncResult);
                        if (device != null && device.IsConnected)
                        {
                            if (SaveHighScore(device))
                            {
                                //Quay lại Menu chính
                                Game1.showMainMenu = true;
                            }
                        }
                    }

                }
                #endregion

                #region Xử lý nút Quay lại
                if (Game1.mouseClickedPosition.X > btnBack_Position.X && Game1.mouseClickedPosition.X < (btnBack_Position.X + btnBack.Width)
                    && Game1.mouseClickedPosition.Y > btnBack_Position.Y && Game1.mouseClickedPosition.Y < (btnBack_Position.Y + btnBack.Height))
                {
                    ReturnGame = true;
                }
                #endregion

                #region Xử lý nút Save
                if (Game1.mouseClickedPosition.X > btnluu_Position.X && Game1.mouseClickedPosition.X < (btnluu_Position.X + btnLuu.Width)
                    && Game1.mouseClickedPosition.Y > btnluu_Position.Y && Game1.mouseClickedPosition.Y < (btnluu_Position.Y + btnLuu.Height)
                    && !Game1.isPlayingNetwork)
                {
                    doSave();
                    Game1.mouseClickedPosition.X = -1;
                }

                #endregion

            }
            catch (Exception e)
            {
                Game1.errorMessage = e.Message;
            }
            base.Update(gameTime);
        }

        
        private void UpdateSaving()
        {
            StorageDevice device = Guide.EndShowStorageDeviceSelector(asyncResult);
            if (device != null && device.IsConnected)
            {
                if (SaveGame(device))
                {
                    //Quay lại Menu chính
                    Game1.showMainMenu = true;
                }
            }
        }

        private bool SaveGame(StorageDevice device)
        {
            string filename;
            string playerName = Gamer.SignedInGamers[PlayerIndex.One].Gamertag;       
            #region Lưu Ván Cờ
            SaveData data = new SaveData();

            data.ktQuanCo = new int[10 * 9];
            for (int i = 0; i < 10; i++)
                for (int j = 0; j < 9; j++)
                    data.ktQuanCo[i * 9 + j] = QuanLyQuanCo.ktQuanCo[i, j];

            data.luotdi = VanCo.LuotDi;

            data.DSQuanCoData = new List<QuanCoData>();
            foreach (QuanCo q in vanco.qlQuanCo.DanhSachQuanCo)
            {
                QuanCoData p = new QuanCoData();
                p.cot = q.cot;
                p.dong = q.dong;
                p.isSelected = false;
                p.quan = q.quan;
                p.ViTriDiChuyen = q.ViTriDiChuyen;
                p.ViTriQuanCo = q.viTriQuanCo;

                 //1: tot
                 //2: phao
                 //3: xe
                 //4: ma
                 //5: tuong
                 //6: si
                 //7: tuong
                if (q is QuanTot)
                    p.texture = 1;
                else if (q is QuanPhao)
                    p.texture = 2;
                else if (q is QuanXe)
                    p.texture = 3;
                else if (q is QuanMa)
                    p.texture = 4;
                else if (q is QuanTuong)
                    p.texture = 5;
                else if (q is QuanSi)
                    p.texture = 6;
                else if (q is QuanGeneral)
                    p.texture = 7;

                data.DSQuanCoData.Add(p);
            }
            #endregion
                    
            #region Saving...
            // Open a storage container.
            StorageContainer container = device.OpenContainer("Co Tuong");

            // Get the path of the save game.
            filename = Path.Combine(container.Path, playerName + ".sav");
            
            // Open the file, creating it if necessary.
            FileStream stream = File.Open(filename, FileMode.Create);

            // Convert the object to XML data and put it in the stream.
            XmlSerializer serializer = new XmlSerializer(typeof(SaveData));            
            serializer.Serialize(stream, data);
            
            // Close the file.
            stream.Close();

            // Dispose the container, to commit changes.
            container.Dispose();
            #endregion

            #region Show MessageBox
            GameSaveRequested = false;
            Guide.BeginShowMessageBox("Co Tuong", "Save Thanh Cong", new string[] {"OK"}, 0,
                MessageBoxIcon.None, endShowMessage, null);
            #endregion

            return true;
        }

        private void doSave()
        {
            if ((!Guide.IsVisible) && (GameSaveRequested == false))
            {
                GameSaveRequested = true;
                asyncResult = Guide.BeginShowStorageDeviceSelector(playerIndex,
                    null, null);
            }

            if ((GameSaveRequested) && (asyncResult.IsCompleted))
            {
                UpdateSaving();
            }
        }

        private bool SaveHighScore(StorageDevice device)
        {
            string playerName = Gamer.SignedInGamers[PlayerIndex.One].Gamertag;
            HighScoreData hsData = new HighScoreData();
            bool flag = false;
            for (int i = 0; i < HighScore.ListPlayer.Count; i++)
            {
                if (playerName.Equals(HighScore.ListPlayer[i].Name))
                {
                    flag = true;
                    break;
                }
            }
            if (!flag)
            {
                HighScore.ListPlayer.Add(new Player(playerName, 0, 0));
            }
            hsData.listPlayerData = HighScore.ListPlayer;

            // Open a storage container.
            StorageContainer container = device.OpenContainer("Co Tuong");

            // Get the path of the save game.
            string filename = Path.Combine(container.Path, "score.hs");

            // Open the file, creating it if necessary.
            FileStream stream = File.Open(filename, FileMode.Create);

            // Convert the object to XML data and put it in the stream.
            XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData));
            serializer.Serialize(stream, hsData);

            // Close the file.
            stream.Close();

            // Dispose the container, to commit changes.
            container.Dispose();

            return true;
        }

        private void endShowMessage(IAsyncResult result)
        {
            int? index = Guide.EndShowMessageBox(result);
            
        }

        public override void Draw(GameTime gameTime)
        {
            Color myTransparentColor = new Color(255, 255, 255, 150);
            spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.None);
            spriteBatch.Draw(SubMenuTexture, SubMenu_Position, Color.White);

            if (isThoatOnHover)
                spriteBatch.Draw(btnThoat, btnThoat_Position, Color.White);
            else
                spriteBatch.Draw(btnThoat, btnThoat_Position, myTransparentColor);

            if (!Game1.isPlayingNetwork)
            {
                if (isLuuOnHover)
                    spriteBatch.Draw(btnLuu, btnluu_Position, Color.White);
                else
                    spriteBatch.Draw(btnLuu, btnluu_Position, myTransparentColor);
            }

            if (isBackOnHover)
                spriteBatch.Draw(btnBack, btnBack_Position, Color.White);
            else
                spriteBatch.Draw(btnBack, btnBack_Position, myTransparentColor);
            spriteBatch.End();

            base.Draw(gameTime);
        }

    }
}
